const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');
const User = require('../models/user.model');
const Shop = require('../models/shop.model');
require('dotenv').config();

// 连接数据库
const connectDB = async () => {
  try {
    await mongoose.connect(process.env.MONGODB_URI || 'mongodb://localhost:27017/jd-mall');
    console.log('✅ 数据库连接成功');
  } catch (error) {
    console.error('❌ 数据库连接失败:', error);
    process.exit(1);
  }
};

// 创建管理员用户
const createAdminUsers = async () => {
  try {
    // 检查是否已存在管理员
    const existingAdmin = await User.findOne({ role: 'admin' });
    if (existingAdmin) {
      console.log('⚠️  管理员用户已存在，跳过创建');
      return;
    }

    // 创建超级管理员
    const adminUser = new User({
      name: 'admin',
      email: 'admin@example.com',
      password: 'admin123',
      phone: '13800138000',
      role: 'admin',
      isActive: true,
      isEmailVerified: true,
      isPhoneVerified: true,
    });

    await adminUser.save();
    console.log('✅ 超级管理员创建成功');
    console.log('   用户名: admin');
    console.log('   密码: admin123');

    // 创建测试店铺
    const testShop = new Shop({
      name: '测试店铺',
      description: '这是一个测试店铺',
      logo: 'https://via.placeholder.com/200x200?text=Shop+Logo',
      banner: 'https://via.placeholder.com/800x300?text=Shop+Banner',
      ownerId: new mongoose.Types.ObjectId(), // 临时ID
      ownerName: '店铺老板',
      status: 'active',
      rating: 4.8,
      totalSales: 1000,
      totalProducts: 50,
    });

    await testShop.save();
    console.log('✅ 测试店铺创建成功');

    // 创建店铺老板
    const sellerUser = new User({
      name: 'seller1',
      email: 'seller1@example.com',
      password: 'seller123',
      phone: '13800138001',
      role: 'seller',
      shopId: testShop._id,
      isActive: true,
      isEmailVerified: true,
      isPhoneVerified: true,
    });

    await sellerUser.save();

    // 更新店铺的ownerId
    testShop.ownerId = sellerUser._id;
    await testShop.save();

    console.log('✅ 店铺老板创建成功');
    console.log('   用户名: seller1');
    console.log('   密码: seller123');

    // 创建客服人员
    const serviceUser = new User({
      name: 'service1',
      email: 'service1@example.com',
      password: 'service123',
      phone: '13800138002',
      role: 'customer_service',
      shopId: testShop._id,
      isActive: true,
      isEmailVerified: true,
      isPhoneVerified: true,
    });

    await serviceUser.save();
    console.log('✅ 客服人员创建成功');
    console.log('   用户名: service1');
    console.log('   密码: service123');

    console.log('\n🎉 所有管理员用户创建完成！');
    console.log('\n📋 登录信息汇总:');
    console.log('┌─────────────┬──────────┬───────────┬──────────────┐');
    console.log('│    角色     │  用户名  │   密码    │     权限     │');
    console.log('├─────────────┼──────────┼───────────┼──────────────┤');
    console.log('│ 超级管理员  │  admin   │ admin123  │   所有权限   │');
    console.log('│ 店铺老板    │ seller1  │ seller123 │ 店铺管理权限 │');
    console.log('│ 客服人员    │ service1 │ service123│ 客服相关权限 │');
    console.log('└─────────────┴──────────┴───────────┴──────────────┘');

  } catch (error) {
    console.error('❌ 创建管理员用户失败:', error);
  }
};

// 主函数
const main = async () => {
  await connectDB();
  await createAdminUsers();

  console.log('\n✨ 脚本执行完成，正在关闭数据库连接...');
  await mongoose.connection.close();
  console.log('✅ 数据库连接已关闭');
  process.exit(0);
};

// 运行脚本
if (require.main === module) {
  main().catch((error) => {
    console.error('❌ 脚本执行失败:', error);
    process.exit(1);
  });
}

module.exports = { createAdminUsers };
